package util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.buf.HexUtils;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;


public class HttpClientTest {




    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            resultString = e.getMessage();
            e.printStackTrace();
        } finally {
            try {
                assert response != null;
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * post请求,签名和报文加密
     *
     * @param url        请求地址
     * @param json       请求json参数
     * @param publicKey  rsa公钥
     * @param privateKey rsa私钥
     * @return
     */
    public static String doPostJsonForSign(String url, String json, String publicKey, String privateKey) {
        String aesKey = AesUtils.generateAesKey();
        Request jsonRequest = new Request();
        jsonRequest.setRequestId(getUUID32());
        jsonRequest.setTimestamp(System.currentTimeMillis());
        //aseKey 加密
        byte[] enStr = RSAUtils.encryptByPublicKey(aesKey, publicKey);
        String aseKeyStr = HexUtils.toHexString(enStr);
        jsonRequest.setAseKey(aseKeyStr);
        //请求参数进行加密
        String body = "";
        try {
            body = AesUtils.aesEncrypt(json, aesKey);
        } catch (Exception e) {
            throw new RuntimeException("报文加密异常", e);
        }
        jsonRequest.setBody(body);
        Map<String, Object> paramMap = RSAUtils.bean2Map(jsonRequest);
        paramMap.remove("sign");
        // 参数排序
        Map<String, Object> sortedMap = RSAUtils.sort(paramMap);
        // 拼接参数：key1Value1key2Value2
        String urlParams = RSAUtils.groupStringParam(sortedMap);
        //私钥签名
        String sign = RSAUtils.sign(urlParams, privateKey);
        jsonRequest.setSign(sign);
        String requestParams = JSONObject.toJSONString(jsonRequest);
        String result = doPostJson(url, requestParams);
        return result;
    }
    public static String getUUID32() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return uuid;
    }

    public static void main(String[] args) {
//         String rsaPub="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8NF5wvTCLVKrWcmWyEXImbG6Dc8qfzavllmtOQIb7nvv42rmxA+4FCkvRrf46HfQratu1JXpy+t2bFtZvRfhUCAwEAAQ==";
/*

        String rsaPrivate="MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvw0XnC9MItUqtZyZ" +
                "bIRciZsboNzyp/Nq+WWa05Ahvue+/jaubED7gUKS9Gt/jod9Ctq27UlenL63ZsW1" +
                "m9F+FQIDAQABAkBP4CFm4z9psMXSeE6M2Cn4Pikm8DljjpnC+3/nw/LX5UMek3JC" +
                "/wW7067g/iYCCaMhFazfiVs/ld85e0l/z2EBAiEA5aU3DsoigGsJK91FW/AL6JtF" +
                "brCfDr4jORtV1izvyf0CIQDU+gL6r8kKfrQuw5zEnfZ8fgBV3dS9qRRw6+PZM01T" +
                "+QIgNGK56o/FyxGfp/fz6IMb1FYHQrbbsdtB4bcQn6jkkmkCIQCP4L52gJ6+ek5b" +
                "cUbNBTHpdG3hlFUOM9VdW963cxMAcQIhAJc9k5OFRbQolVCiRnNHb3aKymIJIQzG" +
                "64GfyZDpidoT";

        //请求地址
        String url = "http://152.136.135.190:8001/tracking/card/create";
        Map<String, Object> request = new HashMap<>();
        request.put("name","Longer");
        request.put("age","10");
        request.put("address","beijing");
        String json = JacksonUtils.beanToJson(request);
        System.out.println("json:"+json);

        String responseBody = HttpClientTest.doPostJsonForSign(url, json,rsaPub,rsaPrivate);
        Response response = JacksonUtils.jsonToBean(responseBody, Response.class);
        System.out.println(JacksonUtils.beanToJson(response));*/
    }
}

